import { defineStore } from 'pinia'
import { convertDesignCompListToMap } from '@/utils/DesignCompUtil'

export const useDesignerStore = defineStore('designerStore', () => {
  /**
   * 组件列表
   */
  const designCompList = ref<DesignComp[]>([])
  /**
   * 当前新增的组件实例id
   */
  const currentAddCompInstanceId = ref('')
  /**
   * 上一个被编辑组件的组件id
   */
  const beforeShowCompSetting = ref<string>('')
  /**
   * 当前被编辑组件的vue组件名
   */
  const showCompSetting = ref<string>('')
  /**
   * 当前被编辑组件的组件信息
   */
  const showCompInfo = ref<DesignComp>()
  /**
   * 页面配置
   */
  const pageSettings = ref<PageSettings>({
    drawSettings: { width: '1440px', height: '900px', bgColor: '#fff', scale: 1 }
  })
  /**
   * key为组件id
   */
  const designCompMap = computed<Map<string, DesignComp>>(() => {
    const map = convertDesignCompListToMap(designCompList.value)
    return map
  })

  const designCompMapSize = computed(() => {
    return designCompMap.value.size
  })

  /**
   * 将指定组件更新为显示，并将上一个显示组件更新为隐藏
   * @param designCompInfo
   */
  function updateCompInfoToShow(designCompInfo: DesignComp) {
    if (beforeShowCompSetting.value && designCompInfo.id !== beforeShowCompSetting.value) {
      const lastShowDesignCompInfo = designCompMap.value.get(beforeShowCompSetting.value)
      if (lastShowDesignCompInfo) {
        lastShowDesignCompInfo.showToolBtn = false
      }
    }
    showCompInfo.value = designCompInfo
    showCompSetting.value = designCompInfo.flag
    beforeShowCompSetting.value = designCompInfo.id
  }
  /**
   * 更新组件工具按钮的显示状态
   * @param showToolBtn 是否显示组件的toggle按钮
   * @param id 组件id
   */
  function toggleToolBtn(showToolBtn: boolean, id: string) {
    const compInfo = designCompMap.value.get(id)
    if (compInfo) {
      compInfo.showToolBtn = showToolBtn
      if (showToolBtn) {
        updateCompInfoToShow(compInfo)
      }
    }
  }
  function recordCurrentAddCompInstanceId(compInstanceId: string) {
    currentAddCompInstanceId.value = compInstanceId
  }
  /**
   * 查找指定组件实例id的所有先辈节点id(不包含本身)
   * @param compInstanceId 待查找组件实例id
   * @returns 返回的结果集合顺序是关系从远到近(类似: [祖先id,爷爷id,父节点id])
   */
  function findAnssertIds(compInstanceId: string) {
    if (!compInstanceId) return []
    return doFindAnssertIds(compInstanceId, designCompList.value)
  }
  function doFindAnssertIds(compInstanceId: string, compList: DesignComp[]) {
    const ret: string[] = []
    for (const item of compList) {
      if (item.id === compInstanceId) {
        return ret
      } else if (item.children && item.children.length > 0) {
        const tmpRet = doFindAnssertIds(compInstanceId, item.children)
        ret.push(item.id, ...tmpRet)
      }
    }
    return ret
  }
  return {
    designCompList,
    designCompMap,
    pageSettings,
    showCompSetting,
    showCompInfo,
    currentAddCompInstanceId,
    designCompMapSize,
    toggleToolBtn,
    updateCompInfoToShow,
    recordCurrentAddCompInstanceId,
    findAnssertIds
  }
})
